package ru.ifmo.cppsc.translator;

import ru.ifmo.cppsc.grammar.Grammar;
import ru.ifmo.cppsc.grammar.Production;
import ru.ifmo.cppsc.auxilary.FileHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.io.*;

import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: orybak
 * Date: 29.06.2008
 * Time: 20:15:01
 * To change this template use File | Settings | File Templates.
 */
public class TranslatorCodeGenerator {
    private static final Logger log = Logger.getLogger(TranslatorCodeGenerator.class.getName());

    public void generateCode ( Grammar grammar ) {
        String beginTemplate = FileHelper.getFileContents ( "./data/beginTemplate.dat" );
        String mapInsertStr = "";

        ArrayList<Production> productions = new ArrayList<Production>();
        productions.addAll(Arrays.asList(grammar.getProductions()));

        int count = 0;
        for (Production prod : productions) {
            mapInsertStr += "        prodMap.put(\""
                    + prod.toString()
                    + "\", new TreeNodeProcessor"
                    + count + "());\n";
        count ++;
        }

        mapInsertStr += "\n    }\n}\n\n";

        String procImplStr = "";
        count = 0;
        for (Production prod: productions) {
            procImplStr += "// " + prod.toString() + "\n"
                    + "class TreeNodeProcessor"
                    + count
                    + " extends ProcessorBase {\n"
                    + "    public void doProcess(TreeNode node) {"
                    + prod.getCode ()
                    + "}\n}\n\n";
            count ++;
        }

        try {
            FileWriter fw = new FileWriter("src\\main\\java\\ru\\ifmo\\cppsc\\translator\\generated\\CodeContainer.java");
            fw.write ( beginTemplate );
            fw.write ( mapInsertStr );
            fw.write ( procImplStr );
            fw.close();
        } catch ( IOException e ) {
            log.fatal( "Can't write CodeContainer.java file to disk." );
        }
    }
}
